const koa = require('koa');
const views = require('koa-views');
const static = require('koa-static');
const Router = require('koa-router');
const bodyParser = require('koa-bodyparser');
const md5 = require('md5');
const session = require('koa-session');
const musicData = require('./data/music.json');

const app = new koa();
const router = new Router();

app.keys = ['some secret hurr'];

app.use(bodyParser());
app.use(session({
    // signed: false
}, app));
app.use(views(__dirname + '/views'), {
    map: {
        html: 'pug'
    }
});

app.use(static(__dirname + '/static'));

router.get('/', (ctx, next) => {
    ctx.redirect('/login');
})

router.get('/login', async (ctx, next) => {
    let cookieInfo = ctx.cookies.get('isLogin');
    if (cookieInfo) {
        let serverInfo = md5('张三' + '123');
        if (serverInfo == cookieInfo) {
            ctx.redirect('/list');
        }
    }
    await ctx.render('login.pug');
});

router.get('/list', async (ctx, next) => {
    console.log(ctx.session.test);
    console.log(ctx.session.test1);
    await ctx.render('list.pug', { musicData });
});

router.get('/detail', async (ctx, next) => {
    await ctx.render('detail.pug');
});

router.get('/error', async (ctx, next) => {
    await ctx.render('error.pug');
});

router.post('/checkUser', (ctx, next) => {
    let body = ctx.request.body;
    // 假定用户名是张三 密码是123
    if (body.username == '张三' && body.pwd == '123') {
        if (body.memberMe == 'on') {
            // 寻要存储登陆成功的状态
            let loginStatus = md5(body.username + body.pwd);
            ctx.cookies.set('isLogin', loginStatus, {
                maxAge: 3600 * 1000 * 24 * 7
            });
            ctx.session.test = 'test';
            ctx.session.test1 = 'test1';
        }
        // 跳转到list页面
        ctx.redirect('/list');
    } else {
        //跳转到错误页面
        ctx.redirect('/error')
    }
});

app.use(router.routes());

app.listen(3000);